package com.ja.openchat.viewmodels;

import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.JsonObject;
import com.ja.openchat.ui.chat.ChatActivity;
import com.ja.openchat.ui.chat.PreviewWebViewActivity;
import com.ja.openchat.ui.me.RechargeSuccessFragment;
import com.ja.openchat.ui.me.WithdrawalAccountFragment;
import com.ja.openchat.views.VerificationCodeView;
import com.ja.openchat.views.VerifyPayPasswordDialog;
import com.lxj.xpopup.XPopup;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.wallet.WalletInfo;
import com.zy.openchat.core.model.wallet.WalletTixianRes;

import java.util.Map;

import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;


public class WithdrawalViewModel extends BaseViewModel {
    public final static String FROM_TYPE = "WithdrawalViewModel";
    //金额
    public ObservableField<String> money = new ObservableField<>("");
    public ObservableField<String> balance = new ObservableField<>("当前钱包余额: ¥0.00");
    public ObservableField<Boolean> enable = new ObservableField<>(false);

    private float accountBalance = 0.00f;

    public WithdrawalViewModel(@NonNull Application application) {
        super(application);
        requestData();
    }

    //提交按钮的点击事件
    public BindingCommand confirmOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            Bundle bundle = new Bundle();
            bundle.putString("money", money.get());
            bundle.putString("fromType", FROM_TYPE);
            startContainerActivity(RechargeSuccessFragment.class.getCanonicalName(), bundle);
        }
    });
    //更换提现账户按钮的点击事件
    public BindingCommand withdrawalAccountOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startContainerActivity(WithdrawalAccountFragment.class.getCanonicalName());
        }
    });

    public void withdraw(float value, Context context) {
        if (value <= 0) {
            ToastUtils.showShort("请输入有效的提现金额");
            return;
        }
        if (accountBalance < value) {
            ToastUtils.showShort("提现金额大于钱包余额");
            return;
        }
        new XPopup.Builder(context)
                .autoOpenSoftInput(true)
                .asCustom(new VerifyPayPasswordDialog(context, String.format("%.2f", value), "提现", new VerificationCodeView.OnInputFinishListener() {
                    @Override
                    public void onInputFinish(String text) {
                        submitWithdraw(value, text);
                    }
                }))
                .show();

    }

    private void submitWithdraw(float value, String password) {
        showProgress();
        TelegramManager.getTelegramManager().WalletTixianRequest(getApplication(), value, password, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (obj != null) {
                    if (obj.errCode == 400) {
                        showErrorTip("余额不足");
                    } else if (obj.errCode == 401) {
                        showErrorTip("钱包密码错误");
                    } else if (obj.errCode == 402) {
                        showErrorTip("钱包密码未设置");
                    } else if (obj.data != null && obj.data instanceof WalletTixianRes) {
                        WalletTixianRes res = (WalletTixianRes) obj.data;
                        if (!TextUtils.isEmpty(res.checkoutUrl)) {
                            Bundle bundle = new Bundle();
                            bundle.putString("url", res.checkoutUrl);
                            bundle.putString("title", "提现");
                            startActivity(PreviewWebViewActivity.class, bundle);
                        } else {
                            toPrivateChat(res.csUserId);
                        }
                    } else {
                        ToastUtils.showShort("请求错误，请稍后重试");
                    }
                } else {
                    ToastUtils.showShort("请求错误，请稍后重试");
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                ToastUtils.showShort("请求超时，请稍后重试");
            }
        });
    }

    private void toPrivateChat(long userId) {
        TelegramManager.getTelegramManager().createPrivateChat(getApplication(), userId, new TgResultBlock<ChatInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, ChatInfo obj) {
                hideProgress();
                if (obj != null) {
                    Bundle bundle = new Bundle();
                    bundle.putParcelable("conversation", obj);
                    startActivity(ChatActivity.class, bundle);
                } else {
                    ToastUtils.showShort("请求错误，请稍后重试");
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                ToastUtils.showShort("请求超时，请稍后重试");
            }
        });
    }

    void requestData() {
        TelegramManager.getTelegramManager().queryWalletInfo(getApplication(), new TgResultBlock<WalletInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, WalletInfo walletInfo) {
                if (walletInfo != null) {
                    accountBalance = walletInfo.balance;
                    balance.set(String.format("当前钱包余额：￥%.2f", walletInfo.balance));
                } else {
                    ToastUtils.showShort("请求超时，请稍后重试");
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                ToastUtils.showShort("请求超时，请稍后重试");
            }
        });
    }
}
